package com.lagou.container;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class StandardService{

    private Integer ports;

    private StandardHost host;
    
    private InputStream resourceAsStream;

    public Integer getPorts() {
        return ports;
    }

    public void setPorts(Integer ports) {
        this.ports = ports;
    }

    public StandardHost getHost() {
        return host;
    }

    public void setHost(StandardHost host) {
        this.host = host;
    }

    public InputStream getResourceAsStream() {
        return resourceAsStream;
    }

    public void setResourceAsStream(InputStream resourceAsStream) {
        this.resourceAsStream = resourceAsStream;
    }

    public StandardService() {
    }

    public StandardService(InputStream resourceAsStream) {
        this.resourceAsStream = resourceAsStream;
    }

    public void init() {
        SAXReader saxReader = new SAXReader();

        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();

            //约定这里只有一个Service和端口
            Element seviceEle = (Element) rootElement.selectSingleNode("//Service");
            //获取所有的端口
            Element port = (Element) seviceEle.selectSingleNode("//Connector");
            Integer portNum = Integer.parseInt(port.attributeValue("port"));
            this.ports = portNum;

            //获取host
            Element host = (Element) seviceEle.selectSingleNode("//Host");
            String name = host.attributeValue("name");
            String appBase = host.attributeValue("appBase");

            StandardHost standardHost = new StandardHost(name, appBase);

            //初始化host
            standardHost.init();

            this.host = standardHost;
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

}
